//
//  IGRemoteControlVC.m
//  jingdongfang
//
//  Created by BOE on 2017/8/23.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGRemoteControlVC.h"
#import "IGRemoteScrollSetVC.h"
#import "IGRemoteControlApi.h"
#import "IGScreenModelVC.h"
#import "IGLightVC.h"
#import "IGTimeSwitchVC.h"
#import "IGToControlPageApi.h"

@interface IGRemoteControlVC ()<UITableViewDelegate, UITableViewDataSource>
{
    BOOL isOn;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *tableHeaderView;
    
@property (nonatomic, strong) IGEquRemoteModel *model;
@property (nonatomic, strong) NSString *macId;
@property (nonatomic, strong) IGRemoteControlApi *remoteApi;
@property (nonatomic, strong) IGToControlPageApi *controlPageApi;
@property (nonatomic, strong) NSArray *numArr;

@end

@implementation IGRemoteControlVC

- (instancetype)initWithMacId:(NSString *)macId {
    self = [super init];
    if (self) {
        self.macId = macId;
    }
    return self;
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _numArr = @[@"0.5", @"1", @"2", @"5", @"10", @"30", @"60", @"120"];
    
//    self.title = @"远程控制";
    self.title = NSLocalizedString(@"Remote Control", nil);

    self.view.backgroundColor = [UIColor mainBackgroundColor];
    self.controlPageApi = [[IGToControlPageApi alloc] initWithMacId:self.macId];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];

    [self requestData];
}

- (void)requestData {
    __weak typeof(self) weakSelf = self;
    [self.controlPageApi startWithDecodeClass:[IGToControlPageResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGToControlPageResp *resp = responseObject;
            IGEquRemoteModel *model = resp.data;
            weakSelf.model = model;
            weakSelf.model.macId = weakSelf.macId;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                
                UILabel *titleLabel = (UILabel *)[self.view viewWithTag:101];
//                titleLabel.text = [NSString stringWithFormat:@"设备名称:%@", model.title];
                titleLabel.text = [NSString stringWithFormat:@"%@:%@", NSLocalizedString(@"Device Name", nil),model.title];

                UIButton *deliGalleryBtn = (UIButton *)[self.view viewWithTag:102];
                deliGalleryBtn.selected = [model.sleep boolValue];
            });
        }
    }];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, -100, 0, 0);
        _tableView.tableHeaderView = self.tableHeaderView;
    }
    return _tableView;
}

- (UIView *)tableHeaderView {
    if (!_tableHeaderView) {
        
        UIImage *image = [UIImage imageNamed:@"Remote_iGallery_On"];
        CGSize size = image.size;
        CGFloat height = (KSCREENWIDTH/3)*size.height/size.width;
        
        _tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 15 + 20 + 15 + height + 15 + 44 + 15)];
        _tableHeaderView.backgroundColor = [UIColor mainBackgroundColor];
        UILabel *titleLabel = [[UILabel alloc] init];
//        titleLabel.text = [NSString stringWithFormat:@"设备名称:%@", self.model.title];
        titleLabel.textColor = [UIColor c4Color];
        titleLabel.font = [UIFont font16];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.tag = 101;
        [_tableHeaderView addSubview:titleLabel];
        
        UIImageView *imgView = [[UIImageView alloc] init];
        [_tableHeaderView addSubview:imgView];
        
        UIButton *deliGalleryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [deliGalleryBtn setTitle:@"休眠" forState:UIControlStateNormal];
        [deliGalleryBtn setTitle:NSLocalizedString(@"Sleep", nil) forState:UIControlStateNormal];
        [deliGalleryBtn setImage:[UIImage imageNamed:@"iGallery_dormant"] forState:UIControlStateNormal];
//        [deliGalleryBtn setTitle:@"唤醒" forState:UIControlStateSelected];
        [deliGalleryBtn setTitle:NSLocalizedString(@"Wakeup", nil) forState:UIControlStateSelected];
        [deliGalleryBtn setImage:[UIImage imageNamed:@"iGallery_wait"] forState:UIControlStateSelected];
        [deliGalleryBtn setTitleColor:[UIColor c4Color] forState:UIControlStateNormal];
        [deliGalleryBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
        deliGalleryBtn.backgroundColor = [UIColor c3Color];
        deliGalleryBtn.layer.masksToBounds = YES;
        deliGalleryBtn.layer.cornerRadius = 22;
//        deliGalleryBtn.selected = [self.model.sleep boolValue];
        deliGalleryBtn.tag = 102;
        imgView.image = deliGalleryBtn.selected?[UIImage imageNamed:@"Remote_iGallery_Off"]:[UIImage imageNamed:@"Remote_iGallery_On"];
        [_tableHeaderView addSubview:deliGalleryBtn];
        __weak typeof(deliGalleryBtn) weakSelBtn = deliGalleryBtn;
        __weak typeof(self) weakSelf = self;
        [deliGalleryBtn setTapActionWithBlock:^{
            
            [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Notice", nil) message:[NSString stringWithFormat:@"%@", [weakSelf.model.sleep boolValue]?NSLocalizedString(@"Confirm to Wake up This Device?", nil):NSLocalizedString(@"Confirm to Wake Hibernate This Device?", nil)] cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    weakSelf.remoteApi = [IGRemoteControlApi new];
                    weakSelf.remoteApi.macId = weakSelf.macId;
                    weakSelf.remoteApi.sleep = weakSelBtn.selected?@"0":@"1";
                    [weakSelf.remoteApi startWithDecodeClass:[IGRemoteControlResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                        if (responseObject) {
                            weakSelf.model.sleep = [weakSelf.model.sleep boolValue]?@"0":@"1";
                            weakSelBtn.selected = [self.model.sleep boolValue];
                            imgView.image = weakSelBtn.selected?[UIImage imageNamed:@"Remote_iGallery_Off"]:[UIImage imageNamed:@"Remote_iGallery_On"];
                        }
                    }];
                }
            }];
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kGAP10);
            make.width.mas_equalTo(KSCREENWIDTH);
            make.centerX.mas_equalTo(_tableHeaderView.mas_centerX);
            make.height.mas_equalTo(kGAP20);
        }];
        
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(titleLabel.mas_bottom).offset(kGAP15);
            make.width.mas_equalTo(KSCREENWIDTH/3);
            make.centerX.mas_equalTo(_tableHeaderView.mas_centerX);
            make.height.mas_equalTo(height);
        }];
        
        [deliGalleryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(imgView.mas_bottom).offset(kGAP15);
            make.centerX.mas_equalTo(_tableHeaderView.mas_centerX);
            make.width.mas_equalTo(KSCREENWIDTH*2/3);
            make.height.mas_equalTo(44);
        }];
        
    }
    
    return _tableHeaderView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

#pragma mark -<UITableViewDelegate,UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"IGShareIgalleryVCID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
    cell.textLabel.font = [UIFont font16];
    cell.textLabel.textColor = [UIColor c4Color];
    cell.detailTextLabel.textColor = [UIColor c5Color];
    cell.detailTextLabel.font = [UIFont font16];
    
    if (indexPath.row == 0)
    {
//        cell.textLabel.text = @"轮播设置";
        cell.textLabel.text = NSLocalizedString(@"Loop Setting", nil);

        //安全性校验 索引小于数组的个数+索引大于0
//        cell.detailTextLabel.text = (([self.model.carousel integerValue] - 1)<self.numArr.count && ([self.model.carousel integerValue] - 1)>=0)?[NSString stringWithFormat:@"%@分", [self.numArr objectAtIndex:([self.model.carousel integerValue] - 1)]]:@"未设置";        
        cell.detailTextLabel.text = (([self.model.carousel integerValue] - 1)<self.numArr.count && ([self.model.carousel integerValue] - 1)>=0)?[NSString stringWithFormat:@"%@%@", [self.numArr objectAtIndex:([self.model.carousel integerValue] - 1)],NSLocalizedString(@"Min", nil)]:NSLocalizedString(@"Unset", nil);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if (indexPath.row == 1)
    {
//        cell.textLabel.text = @"清除缓存";
        cell.textLabel.text = NSLocalizedString(@"Clean Cache", nil);
    }
    else if (indexPath.row == 2)
    {
//        cell.textLabel.text = @"定时开关机";
        cell.textLabel.text = NSLocalizedString(@"Timer Switch", nil);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if (indexPath.row == 3)
    {
//        cell.textLabel.text = @"亮度调节";
        cell.textLabel.text = NSLocalizedString(@"Brightness", nil);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if (indexPath.row == 4)
    {
//        cell.textLabel.text = @"屏幕模式";
        cell.textLabel.text = NSLocalizedString(@"Screen Mode", nil);
//        cell.detailTextLabel.text = [self.model.plates isEqualToString:@"0"] ? @"横屏" : @"竖屏";
        cell.detailTextLabel.text = [self.model.plates isEqualToString:@"0"] ? NSLocalizedString(@"Horizontal screen", nil) : NSLocalizedString(@"Vertical screen", nil);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
  
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0)
    {
        IGRemoteScrollSetVC *setVC = [[IGRemoteScrollSetVC alloc] initWithModel:self.model];
        [UIViewController ig_pushViewController:setVC animated:YES];
    }
    else if (indexPath.row == 1)
    {
        __weak typeof(self) weakSelf = self;
        [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Clean Cache", nil) message:NSLocalizedString(@"Delete all pictures stored on this device?", nil) cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                weakSelf.remoteApi = [IGRemoteControlApi new];
                weakSelf.remoteApi.macId = weakSelf.macId;
                weakSelf.remoteApi.clear = @"1";
                [weakSelf.remoteApi startWithDecodeClass:[IGRemoteControlResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                    if (responseObject) {
                        dispatch_async(dispatch_get_main_queue(), ^{
//                            [weakSelf presentMessageTips:@"清除成功"];
                            [weakSelf presentMessageTips:NSLocalizedString(@"Deleted Successfully", nil)];

                        });
                    }
                }];
            }
        }];
    }
    else if (indexPath.row == 2)
    {
        IGTimeSwitchVC *setVC = [[IGTimeSwitchVC alloc] initWithModel:self.model];
        [UIViewController ig_pushViewController:setVC animated:YES];
    }
    else if (indexPath.row == 3)
    {
        IGLightVC *setVC = [[IGLightVC alloc] initWithModel:self.model];
        [UIViewController ig_pushViewController:setVC animated:YES];
    }
    else if (indexPath.row == 4)
    {
        IGScreenModelVC *setVC = [[IGScreenModelVC alloc] initWithModel:self.model];
        [UIViewController ig_pushViewController:setVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return .01f;
}
    
@end


